//
//  ETSignedInAlertController.swift
//  SwiftDemo2
//
//  Created by ShareAnimation on 2017/11/2.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText

class ETSignedInAlertController: UIViewController {

    fileprivate var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    fileprivate var panelView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 6
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.3
        view.layer.shadowOffset = CGSize(width: 1, height: 1)
        view.backgroundColor = UIColor.white
        return view
    }()
    
    fileprivate var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont(name: "PingFangSC-Regular", size: 18)
        label.text = "您已经在工地很久，是否忘记签入？需要一键补签吗？"
        label.textAlignment = .center
        return label
    }()
    
    fileprivate var leftButton: UIButton = {
        let button = UIButton()
        button.setTitle("不要签入", for: .normal)
        button.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 18)
        button.setTitleColor(UIColor.black, for: .normal)
        return button
    }()
    
    fileprivate var rightButton: UIButton = {
        let button = UIButton()
        button.setTitle("快速签入", for: .normal)
        button.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 18)
        button.setTitleColor(UIColor.init(red: 16/255, green: 142/255, blue: 233/255, alpha: 1), for: .normal)
        return button
    }()
    
    fileprivate var descriptionLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        return label
    }()
    
    fileprivate var closeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage.init(named: "close"), for: .normal)
        button.imageView?.contentMode = .scaleAspectFit
        return button
    }()
    
    private var okHandler: (()->Void)?

    
    var demandBaseMigrantWorkerID: String?
    
    var timer: Timer!
    var timeOut: Int = 30
    
    init (_  okHandler: @escaping ()-> Void){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = okHandler
    }
    
    
    init (demandBaseMigrantWorkerID: String?,timeOut: Int = 60){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.demandBaseMigrantWorkerID = demandBaseMigrantWorkerID
        self.timeOut = timeOut
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.rightButton.addTarget(self, action: #selector(doRightAction), for: .touchUpInside)
        self.leftButton.addTarget(self, action: #selector(doLeftAction), for: .touchUpInside)
        self.closeButton.addTarget(self, action: #selector(doCloseAction), for: .touchUpInside)
        self.setupViews()
        
        self.timer = Timer.init(timeInterval: 1, target: self, selector: #selector(doTimerAction(_:)), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer, forMode: .commonModes)
    }
    
    private func setupViews() {
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        self.view.addSubview(self.panelView)
        self.panelView.snp.makeConstraints { (make) in
            make.left.equalTo(45)
            make.right.equalTo(-45)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view)
        }
        
        self.view.addSubview(self.closeButton)
        self.closeButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.panelView.snp.right)
            make.centerY.equalTo(self.panelView.snp.top)
            make.width.height.equalTo(30)
        }
        
        self.panelView.addSubview(self.titleLabel)
        self.titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.panelView).offset(15)
            make.left.equalTo(self.panelView).offset(10)
            make.right.equalTo(self.panelView).offset(-10)
        }
        
        let horizontalLine1 = UIView()
        horizontalLine1.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(horizontalLine1)
        horizontalLine1.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        
        self.panelView.addSubview(self.leftButton)
        self.leftButton.snp.makeConstraints { (make) in
            make.left.equalTo(self.panelView)
            make.top.equalTo(horizontalLine1.snp.bottom)
            make.height.equalTo(50)
        }
        
        let verticalLine = UIView()
        verticalLine.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(verticalLine)
        verticalLine.snp.makeConstraints { (make) in
            make.top.equalTo(horizontalLine1.snp.bottom)
            make.bottom.equalTo(self.leftButton)
            make.width.equalTo(1)
            make.left.equalTo(self.leftButton.snp.right)
        }
        
        self.panelView.addSubview(self.rightButton)
        self.rightButton.snp.makeConstraints { (make) in
            make.right.equalTo(self.panelView)
            make.left.equalTo(verticalLine.snp.right)
            make.height.equalTo(self.leftButton)
            make.top.equalTo(horizontalLine1.snp.bottom)
            make.width.equalTo(self.leftButton)
        }
        
        let horizontalLine2 = UIView()
        horizontalLine2.backgroundColor = UIColor(red: 243/255, green: 243/255, blue: 243/255, alpha: 1)
        self.panelView.addSubview(horizontalLine2)
        horizontalLine2.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.panelView)
            make.top.equalTo(self.rightButton.snp.bottom)
            make.height.equalTo(1)
        }

        self.panelView.addSubview(self.descriptionLabel)
        self.descriptionLabel.snp.makeConstraints { (make) in
            make.top.equalTo(horizontalLine2.snp.bottom).offset(5)
            make.left.right.equalTo(self.panelView)
            make.bottom.equalTo(self.panelView).offset(-5)
        }
    }
    
    @objc fileprivate func doRightAction() {
        
        self.signedIn { (isSuccess) in
            if isSuccess {
//                self.updateAutoSignedInState()
                WWSuccess("签入成功!")
                
            }
            else {
                WWError("快速签入失败!")
            }
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    @objc fileprivate func doLeftAction() {
        self.updateAutoSignedInState(.ignore)
    }
    
    @objc fileprivate func doCloseAction() {
        self.updateAutoSignedInState(AlertSignedInOption.everyHalfHour)
    }
    
    @objc func doTimerAction(_ timer: Timer) {
        if self.timeOut <= 0 {
            timer.invalidate()
            self.updateAutoSignedInState(.once)
        }
        else {
            self.timeOut -= 1
            self.descriptionLabel.text = "\(self.timeOut)后将自动签入"
        }
    }
    
    //快速签入
    private func signedIn(_ completion:@escaping (Bool) -> Void) {
//        WWBeginLoadingWithStatus("自动签入中")
        
        var guid: String?
        
        let _dispatchGroup = DispatchGroup()
        
        _dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else{
            }
            _dispatchGroup.leave()
        }
        
        _dispatchGroup.notify(queue: DispatchQueue.main) {
            guard guid != nil else {
               
                completion(false)
                return
            }
            guard self.demandBaseMigrantWorkerID != nil else{
                completion(false)
                return
            }
            RecordModel.fastRecord(guid:guid!,demandBaseMigrantWorkerId: self.demandBaseMigrantWorkerID!, signedType: SignedType.signedIn){(response) in
                if response.success {
                   
                    completion(true)
                    NotificationCenter.default.post(name: NSNotification.Name.init(kNotificationAlertSignedInSignedOut), object: nil)
                }
                else {
                   
                    completion(false)
                }
            }
        }
    }
    
    //更新自动签入的方式
    fileprivate func updateAutoSignedInState(_ signedInType: AlertSignedInOption) {
        guard self.demandBaseMigrantWorkerID != nil else {
            WWError("错误")
            self.dismiss(animated: true, completion: nil)
            return
        }
        
        WWBeginLoadingWithStatus("设置提醒方式")
        AutoSignedInModel.updateAutoSignedInType(self.demandBaseMigrantWorkerID!, autoSignedInType: signedInType) { (response) in
            if response.success {
                
                WWSuccess("设置成功")
            }
            else {
                WWError("设置失败")
            }
            self.dismiss(animated: true, completion: nil)
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.timer.invalidate()
    }
}

extension ETSignedInAlertController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SignedInAlertControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return SignedInAlertControllerTransitionDismiss()
    }
}

class SignedInAlertControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! ETSignedInAlertController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        let panelView = toVc.panelView
        let coverview = toVc.coverView
        coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        panelView.alpha = 0.3
        panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
        UIView.animate(withDuration:0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
            panelView.transform = CGAffineTransform.identity
            panelView.alpha = 1
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromView!)
            toVc.view.sendSubview(toBack: fromView!)
        }
    }
}

class SignedInAlertControllerTransitionDismiss: NSObject,UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from) as! ETSignedInAlertController
        
        //        let panelView = fromVc.panelView
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        }) { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
